
package com.rpay.admin.config.jwt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * <p/>
 * JTW验证
 */
@Component
public class JsonWebTokenAuthenticationFilter extends RequestHeaderAuthenticationFilter {
    private boolean exceptionIfHeaderMiss = false;
    private String principalRequest = "Authorization";

    public JsonWebTokenAuthenticationFilter() {
        // Don't throw exceptions if the header is missing
        this.setExceptionIfHeaderMissing(exceptionIfHeaderMiss);
        // This is the request header it will look for
        this.setPrincipalRequestHeader(principalRequest);
        this.setCheckForPrincipalChanges(false);
    }

    @Override
    @Autowired
    public void setAuthenticationManager(
            AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    /**
     *
     */
    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        /*if("options".equalsIgnoreCase(request.getMethod())) {
            return "N/A";
        }*/
        String principal = request.getHeader(principalRequest);

        if (principal == null && exceptionIfHeaderMiss) {
            throw new PreAuthenticatedCredentialsNotFoundException(principalRequest
                    + " header not found in request.");
        } //else {
            //if(!StringUtils.isEmpty(principal)) {
               // principal = principal.substring(7);
          //  }
        //}
        return principal;
    }

}